package com.jie.service.impl;

import com.jie.constant.CacheKey;
import com.jie.enums.SendCodeEnum;
import com.jie.enums.BizCodeEnum;
import com.jie.service.NotifyService;
import com.jie.utils.CommonUtil;
import com.jie.utils.JsonData;
import com.jie.vo.EmailVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class NotifyServiceImpl implements NotifyService {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    //有效时间
    private static final int CODE_EXPEDIENT = 60;

    /**
     * 邮箱发送的核心方法
     *
     * @param sendCodeEnum
     * @param to
     * @return
     */
    @Override
    public JsonData sendCode(SendCodeEnum sendCodeEnum, EmailVO emailVO) {
        ValueOperations<String, String> redis = redisTemplate.opsForValue();
        String randomCode = CommonUtil.getRandomCode(6);
        String captchaValue = randomCode + "_" + CommonUtil.getCurrentTime();
        //缓存key
        String cacheKey = String.format(CacheKey.CHECK_CODE_KEY, sendCodeEnum.name(), emailVO.getTo());
        String key = redis.get(cacheKey);
        //判断是否为空
        if (StringUtils.isNotBlank(key)) {
            //判断是否重复发送 当前时间戳-之前即可
            long ttl = Long.parseLong(captchaValue.split("_")[1]);
            //当前时间戳-验证码发送时间戳，如果⼩于60秒，则不给᯿复发送
            if (CommonUtil.getCurrentTime() - ttl < 1000 * 60) {
                log.info("测试｛｝",CommonUtil.getCurrentTime());
                log.info("请勿复发送验证码,时间间隔: {} 秒", (CommonUtil.getCurrentTime() - ttl) / 1000);
                return JsonData.buildResult(BizCodeEnum.CODE_LIMITED);
            }
        }
        redis.set(cacheKey, captchaValue, CODE_EXPEDIENT, TimeUnit.SECONDS);
        try {
            emailVO.setRandomCode(randomCode);
            rabbitTemplate.convertAndSend("mail.QQ",emailVO);
        } catch (Exception e) {
            return JsonData.buildResult(BizCodeEnum.CODE_QQ_ERROR);
        }
        return JsonData.buildSuccess("发送成功");
    }
}
